package com.catazy.jetpackstudy.act2.chapter2.aidl;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.catazy.jetpackstudy.R;

import java.util.List;

/**
 * - 作者: Tao
 * - 日期: 2025/2/6
 * - 时间: 11:44
 * - 描述:
 */
public class BookManagerActivity extends AppCompatActivity {

    private IBookManager mRemoteBookManager;

    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(android.content.ComponentName name, android.os.IBinder service) {
            mRemoteBookManager = IBookManager.Stub.asInterface(service);
            try {
                List<Book> bookList = mRemoteBookManager.getBookList();
                Log.d("BookManagerActivity", "bookList = " + bookList);
                mRemoteBookManager.addBook(new Book(3, "Android开发艺术探索"));
                Log.d("BookManagerActivity", "添加新书！");
                List<Book> newList = mRemoteBookManager.getBookList();
                Log.d("BookManagerActivity", "newList = " + newList);
                mRemoteBookManager.registerListener(mListener);
            } catch (android.os.RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mRemoteBookManager = null;
        }
    };

    private IOnNewBookArrivedListener mListener = new IOnNewBookArrivedListener.Stub() {
        @Override
        public void onNewBookArrived(Book newBook) throws RemoteException {
            Log.d("BookManagerActivity", "onNewBookArrived, newBook = " + newBook);
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_manager);
        Intent intent = new Intent(this, BookManagerService.class);
        bindService(intent, mConnection, BIND_AUTO_CREATE);
    }

    @Override
    protected void onDestroy() {
        if (mRemoteBookManager != null && mRemoteBookManager.asBinder().isBinderAlive()){
            try {
                mRemoteBookManager.unregisterListener(mListener);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        unbindService(mConnection);
        super.onDestroy();
    }
}
